package com.shareppy.norman.conversion;

import java.lang.reflect.Field;
import java.util.Map;

import org.json.JSONObject;

import com.shareppy.norman.core.annotations.Inherited;
import com.shareppy.norman.core.entity.AbstractEntity;
import com.shareppy.utils.ReflectionUtils;
import com.shareppy.utils.conversion.Converter;

public class EntityJsonConverter<E extends AbstractEntity> implements
		Converter<E, JSONObject> {

	private Map<String, String> keys;

	public EntityJsonConverter() {
		this(null);
	}

	public EntityJsonConverter(Map<String, String> keys) {
		this.keys = keys;
	}

	@Override
	public JSONObject convert(E entity) throws Exception {
		JSONObject json = new JSONObject();
		Field[] fields = ReflectionUtils.getFields(entity, Inherited.class);
		for (Field field : fields) {
			String key = getKey(field.getName());
			if ("".equals(key)) {
				continue;
			}
			json.put(key, ReflectionUtils.getFieldValue(entity, field));
		}
		return json;
	}

	private String getKey(String name) {
		if (this.keys == null) {
			return name;
		}
		String customKey = this.keys.get(name);
		if (customKey == null) {
			return name;
		}
		return customKey;
	}
}